package x7.heatctrl;

import java.io.File;
import java.util.ArrayList;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.ServletHandler;

public class Runner {
	


	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {

		
		// read config
		Config conf = Config.INSTANCE;
		conf.checkForUpdate();

		// HttpServer
		Server server = new Server(Integer.parseInt(System.getProperty("http.port","80")));
		ServletHandler handler = new ServletHandler();
		handler.addServletWithMapping(UIServlet.class,System.getProperty("http.path","/*") );
		server.addHandler(handler);
		server.start();

		// init weather
		long lastLog=0;
		
		// run
		while (true) {
			
			// write weather to db
			if (conf.getWeather()!=null && System.currentTimeMillis()-lastLog>Config.INSTANCE.getLogInterval()*1000 ) {
				// update weather-data
				if (conf.getWeather().update() && System.getProperty("writeWeather", "true").startsWith("t")) {
					DBFile.INSTANCE.add("insert into weather (Time, Temperature, Pressure) values ('"+
							Room.currentTimeStamp()+"',"+conf.getWeather().getCurrentTemperature()+","+conf.getWeather().getCurrentPressure()+")");
				}
				lastLog = System.currentTimeMillis();
			}
			
			// check rooms
			for ( Room r:conf.getRooms()) r.check();
			
			
			// write current values to file
			if (conf.isWriteStatus())  conf.writeStateLog();
			
			// sleep
			try {
				Thread.sleep(conf.getCheckInterval()*1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				System.exit(0);
			}

			// update config
			conf.checkForUpdate();

		}
		
	}

}
